/*
 * @(#)UnicodeUtil.java   1.0  2019年4月18日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.util.type;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2019年4月18日
 */
public class UnicodeUtil {

    /**
     * 单字符串转换unicode
     * @param string
     * @return
     */
    public static String stringToUnicode(String string) {
        if (TypeUtil.isNull(string)) {
            return string;
        }
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /**
     * 单unicode 转字符串
     * 
     * @param unicode
     * @return
     */
    public static String unicodeToString(String unicode) {
        if (TypeUtil.isNull(unicode)) {
            return unicode;
        }
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 0; i < hex.length; i++) {
            String change = "";
            String noChange = "";
            if (hex[i].length() > 4) {
                change = hex[i].substring(0, 4);
                noChange = hex[i].substring(4);
            } else {
                change = hex[i];
            }
            // 追加成string
            string.append(changeStr(change, noChange));
        }
        return string.toString();
    }

    private static String changeStr(String change, String noChange) {
        try {
            if (change.length() <= 0) {
                return noChange;
            }
            // 转换出每一个代码点
            int data = Integer.parseInt(change, 16);
            return (char) data + noChange;
        } catch (Exception ex) {
            String newchange = change.substring(0, change.length() - 1);
            String newnoChange = change.substring(change.length() - 1) + noChange;
            if (newchange.length() <= 0) {
                return newnoChange;
            }
            return changeStr(newchange, newnoChange);
        }
    }

}
